#include "FileLocker.h"

using namespace std;

FileLocker :: FileLocker ( char* name ) {

	strcpy ( this->name,name );

	this->fl.l_type = F_WRLCK;
	this->fl.l_whence = SEEK_SET;
	this->fl.l_start = 0;
	this->fl.l_len = 0;
	this->fl.l_pid = getpid ();
	this->fd = open ( this->name,O_CREAT | O_APPEND |O_RDWR,0777 );
}

int FileLocker :: getLock () {
	this->fl.l_type = F_WRLCK;
	int result = fcntl ( this->fd,F_SETLKW,&(this->fl) );
	return result;
}

int FileLocker :: releaseLock () {
	this->fl.l_type = F_UNLCK;
	int result = fcntl ( this->fd,F_SETLK,&(this->fl) );
	return result;
}

int FileLocker :: writeToFile ( char* buffer,int buffsize ) {
	lseek ( this->fd,0,SEEK_END );
	int result = write ( this->fd,buffer,buffsize );
	return result;
}

string FileLocker :: readFromFile ( int* currentPosition ) {
	int eof = this->getFileSize();
	int size = eof - *currentPosition;
	string messages = "";

	if(size > 0){
		lseek ( this->fd,*currentPosition,SEEK_SET);
		char c[size];
		read ( this->fd,c,size);
		*currentPosition = eof;
		messages.append(c, size);
	}

	return messages;
}

int FileLocker :: getFileSize(){
	return lseek ( this->fd,0,SEEK_END );
}

FileLocker :: ~FileLocker () {
	close ( this->fd );
}
